﻿using LuShanTea.Service.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LuShanTea.Service
{
    public class BaseService<T> where T : BaseEntity
    {
        // 保证对象唯一性
        private LuShanTeaContext ctx;

        public BaseService(LuShanTeaContext ctx)
        {
            this.ctx = ctx;
        }

        /// <summary>
        /// 获取该对象中所有未软删除的数据
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> GetAll()
        {
            return ctx.Set<T>().Where(e => e.IsDeleted == false);
        }

        /// <summary>
        /// 获取没有被乱删除的所有数据总和
        /// </summary>
        /// <returns></returns>
        public long GetTotalCount()
        {
            return GetAll().Count();
        }

        /// <summary>
        /// 分页获取没有被软删除的数据
        /// </summary>
        /// <param name="startIndex">起始数据下标</param>
        /// <param name="count">获取多少条</param>
        /// <returns></returns>
        public IQueryable<T> GetPageData(int startIndex, int count)
        {
            return GetAll().OrderBy(e => e.CreateDateTime).Skip((startIndex-1)*count).Take(count);
        }

        /// <summary>
        /// 根据用户传入的id，获取该对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T GetById(long id)
        {
            return GetAll().Where(e => e.Id == id).SingleOrDefault();
        }

        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="id"></param>
        public void MakeDelete(long id)
        {
            var data = GetById(id);
            if (data != null)
            {
                data.IsDeleted = true;
            }
            ctx.SaveChanges();
        }
    }
}
